package springbook.user.user.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;



import springbook.user.dao.ConnectionMaker;
import springbook.user.dao.DConnectionMaker;
//import springbook.user.dao.SimpleConnectionMaker;
import springbook.user.domain.User;

/*JDBC를 이용한 등록과 조회 기능이 있는 클래스*/
public class UserDao {
	private ConnectionMaker connectionMaker; /*초기에 설정하면 사용중에는 바뀌지 않는 읽기 전용 인스턴스 변수*/
	/*매번 새로운 값으로 바뀌는 정보를 담은 인스턴스 변수. 심각한 문제가 발생한다.*/
	//private Connection c;
	//private User user;
	

	public void setConnectionMaker(ConnectionMaker connectionMaker) {
		this.connectionMaker = connectionMaker;
	}

	public UserDao(){}

	public UserDao(ConnectionMaker connectionMaker){ //생성자 의존관계주입법
		this.connectionMaker = connectionMaker;
	}
	
	
	
	/*
	 * private static UserDao INSTANCE;
	private UserDao(ConnectionMaker connectionMaker){
		this.connectionMaker = connectionMaker;
	}
	public static synchronized UserDao getInstance(){
		if(INSTANCE == null) INSTANCE = new UserDao(connectionMaker); private로 바뀐 생성자는 이제 ConnectionMaker 오브젝트를 넣어주는것이 불가능해졌다.
		return INSTANCE;
		
		스프링 싱글톤 레지스트리.
	}*/
	
	public void add(User user) throws ClassNotFoundException, SQLException{
		Connection c = connectionMaker.makeConnection();
		
		String sql = "insert into users(id,name,password) values(?,?,?)";
		PreparedStatement ps = c.prepareStatement(sql);
		
		ps.setString(1, user.getId());
		ps.setString(2, user.getName());
		ps.setString(3, user.getPassword());
		
		ps.executeUpdate();
		ps.close();
		c.close();
	}
	public User get(String id) throws ClassNotFoundException, SQLException{
		/*DB에 있는 값을 불러와 값 셋팅*/
		Connection c = connectionMaker.makeConnection();
		
		String sql = "select * from users where id=?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setString(1, id);
		
		ResultSet rs = ps.executeQuery();
		rs.next();
		
		User user = new User();
		user.setId(rs.getString("id"));
		user.setName(rs.getString("name"));
		user.setPassword(rs.getString("password"));
		
		rs.close();
		ps.close();
		c.close();
		return user;
	}
	
	//public abstract Connection getConnection() throws ClassNotFoundException, SQLException;
	/*{
		Class.forName("com.mysql.jdbc.Driver");
		String url = "jdbc:mysql://localhost:3306/spring";
		String dbuser = "springuser";
		String dbpassword = "springpassword";
		Connection c = DriverManager.getConnection(url, dbuser, dbpassword);
		return c;
	}*/
}
